let preEl;
let preBackgroundColor;

const onmousemove = debounce((e) => {
  const { pageX, pageY } = e;
  // 根据坐标获取指定的元素
  const el = document.elementFromPoint(pageX, pageY);
  console.log(pageX, pageY, el, getDocumentObj(el));
  if (preEl) {
    preEl.style.backgroundColor = preBackgroundColor;
  }

  if (el) {
    preBackgroundColor = el.style.backgroundColor;
    preEl = el;
    el.style.backgroundColor = 'aqua';

    copySelector(el);
  }
}, 30);

document.onmousemove = onmousemove;

// 防抖
function debounce(fn, delay) {
  let timer;
  return (...args) => {
    timer && clearTimeout(timer);
    timer = setTimeout(() => {
      fn.apply(this, args);
    }, delay);
  };
};

////////////////////////////

function getDocumentObj(element) {
  const result = {};
  for (const key in element) {
    result[key] = element[key];
  }
  return result;
}

// 根据元素获取生成对应的选择器
function copySelector(element) {
	// 生成选择器
	function generateSelector(el) {
    if (!el || el.tagName === "HTML") {
      return "";
    }
		const tagName = el.tagName.toLowerCase();
		const className = el.className ? `.${el.className.replace(/\s+/g, ".")}` : "";
		const id = el.id ? `#${el.id}` : "";

		let attributeSelector = "";
		// const attr = Array.from(el.attributes).find((attr) => attr.name !== "class" && attr.name !== "id");

		// if (attr) {
		// 	attributeSelector = attr.name ? `[${attr.name}="${attr.value}"]` : "";
		// }

    // previousElementSibling: 上一个节点
    // parentNode: 父级
    // children 如果下面的都是相同的元素, 类名(可能会有不同), id名, 则视为同级
    // 多个相同的元素, 如: div 则合并成一个
		if (el.parentNode !== document.body) {
			return `${generateSelector(el.parentNode)} > ${tagName}${className}${id}${attributeSelector}`;
		} else {
			return `${tagName}${className}${id}${attributeSelector}`;
		}
	}

	const selector = generateSelector(element);
  console.log("selector: ", selector);
	// copyToClipboard(selector);
}


// 复制到剪贴板
async function copyToClipboard(text) {
  try {
    await navigator.clipboard.writeText(text);
    console.log("Selector: ", text);
    if (text) {
      const selectorEl = document.querySelector(text);
      console.log("selectorEl: ", selectorEl);
    }
  } catch (err) {
    console.error("Error copying to clipboard:", err);
  }
}
